package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.qo.PageResult;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.RequiredPermission;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.*;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private ApplicationContext ctx;

    @Override
    public void save(Permission Permission) {
        permissionMapper.insert(Permission);
    }

    @Override
    public void delete(Long id) {
        permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Permission Permission) {
        permissionMapper.updateByPrimaryKey(Permission);
    }

    @Override
    public Permission selectOne(Long id) {
        return permissionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Permission> listAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public List<Permission> queryForData(QueryObject qo) {
        return permissionMapper.queryForData(qo);
    }

    @Override
    public PageInfo<Permission> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Permission> permissions = permissionMapper.queryForData(qo);
        return new PageInfo<>(permissions);

        /*int count = permissionMapper.queryForCount(qo);
        return new PageResult<>(qo.getCurrentPage(),qo.getPageSize(),count,
                count == 0 ?
                Collections.emptyList() : permissionMapper.queryForData(qo));*/
    }

    /*@Override
    public int queryForCount(QueryObject qo) {
        int totalCount = permissionMapper.queryForCount(qo);
        return totalCount;
    }*/

    @Override
    public void reload() {
        List<Permission> permissions = permissionMapper.selectAll();
        HashSet<String> expressions = new HashSet<>();
        for (Permission permission : permissions) {
            expressions.add(permission.getExpression());
        }
        Collection<Object> collections = ctx.getBeansWithAnnotation(Controller.class).values();
        for (Object collection : collections) {
            //判断当前对象时候为cglib代理对象
            if (!AopUtils.isCglibProxy(collection)) {
                continue;
            }


            //贴了shiro注解的控制器，都会被代理，获取到的就是代理对象，从代理对象获取不到注解吗，需要他的父类对象
            Method[] methods = collection.getClass().getSuperclass().getMethods();
            for (Method method : methods) {
                RequiresPermissions annotation = method.getAnnotation(RequiresPermissions.class);
                if (annotation != null && !expressions.contains(annotation.value()[0])) {
                    permissionMapper.insert(new Permission(annotation.value()[1], annotation.value()[0]));
                }
            }
        }





        /*//先把数据库所有权限数据查询出来
        List<Permission> permissions = permissionMapper.selectAll();
        HashSet<String> expressions = new HashSet<>();
        for (Permission permission : permissions) {
            expressions.add(permission.getExpression());
        }
        //获取所有的控制器的处理方法
        //通过 Spring 容器获取所有控制器对象
        Map<String, Object> beans = ctx.getBeansWithAnnotation(Controller.class);
        Collection<Object> controllers = beans.values();
        //获取遍历每个控制器对象，反射获取通过其对象的字节码获取其里面所有方法
        for (Object controller : controllers) {
            Method[] methods = controller.getClass().getDeclaredMethods();
            //获取方法上的注解
            for (Method method : methods) {
                //方法上有贴我们的自定义注解
                RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
                if (annotation != null) {
                    //获取方法上的注解 name 和 expression 值
                    String name = annotation.name();
                    String expression = annotation.expression();
                    //存入到数据库之前要判断一下，若数据库中不存在就存入
                    if (!permissions.contains(expression)){
                        //创建Permission对象，封装上面的值，调用permissionMapper的保存数据方法
                        Permission permission = new Permission();
                        permission.setName(name);
                        permission.setExpression(expression);
                        permissionMapper.insert(permission);
                    }
                }
            }
        }*/




















        /*//先把数据库所有权限数据查询出来
        List<Permission> permissions = permissionMapper.selectAll();
        Set<String> expressions = new HashSet<>();
        for (Permission permission : permissions) {
            expressions.add(permission.getExpression());
        }

        //获取所有的控制器的处理方法
        //通过 Spring 容器获取所有控制器对象
        Map<String, Object> beans = ctx.getBeansWithAnnotation(Controller.class);
        Collection<Object> controllers = beans.values();
        //获取遍历每个控制器对象，反射获取通过其对象的字节码获取其里面所有方法
        for (Object controller : controllers) {
            Method[] methods = controller.getClass().getDeclaredMethods();
            for (Method method : methods) {
                //获取方法上的注解
                RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
                //方法上有贴我们的自定义注解
                if (annotation != null) {

                    //获取方法上的注解 name 和 expression 值
                    String name = annotation.name();
                    String expression = annotation.expression();

                    //存入到数据库之前要判断一下，若数据库中不存在就存入
                    if (!expressions.contains(expression)){

                        //创建Permission对象，封装上面的值，调用permissionMapper的保存数据方法
                        Permission permission = new Permission();
                        permission.setName(name);
                        permission.setExpression(expression);
                        permissionMapper.insert(permission);
                    }

                }
            }

        }*/


    }

    @Override
    public List<String> queryByEmployeeId(Long employeeId) {
        return permissionMapper.queryByEmployeeId(employeeId);
    }
}
